import {isRealNode} from "../../../core/vdom/utils";
import {updateListeners} from "../../../core/vdom/helpers/update-listeners";
import {isDef} from "../../../shared/util";
import {VIRTUAL_NODE_TYPE} from "../../../constant";

let target = null;

function add (event, handler) {
    target.addEventListener(event, handler);
}

function remove (event, handler) {
    target.removeListener(event, handler);
}

function updateEvents (oldNode, newNode) {

    if (newNode.nodeType !== VIRTUAL_NODE_TYPE.ELEMENT) {
        return;
    }

    let elem = null;
    let isOldNodeReal = false;
    if (isRealNode(oldNode)) {
        elem = oldNode;
        isOldNodeReal = true;
    }
    else {
        elem = newNode.elem;
    }

    let vm = newNode.context;
    target = elem;
    if (isOldNodeReal) {
        const staticListeners = newNode.data.on;
        updateListeners(vm, staticListeners, {}, add, remove);
        if (isDef(newNode.data.bindOn)) {
            const bindListeners = newNode.data.bindOn;
            updateListeners(vm, bindListeners, {}, add, remove);
        }
    }
    else {
        let oldBindListeners = null;
        isDef(oldNode.data.bindOn)
            ? oldBindListeners = oldNode.data.bindOn
            : oldBindListeners = {};
        let newBindListeners = null;
        isDef(newNode.data.bindOn)
            ? newBindListeners = newNode.data.bindOn
            : newBindListeners = {};
        updateListeners(vm, newBindListeners, oldBindListeners, add, remove);
    }
}

export default {
    mount: updateEvents,
    update: updateEvents,
}
